The Grammar of Graphics

The package we’re going to use for our graphing is called ggplot2, which was written by Hadley Wikham before he developed the tidyverse. It is based on one of the most celebrated academic books on visualization, called the “Grammar of Graphics” by Leland Wilkinson in the 1980s. For our purposes, you just need to understand that any visualization is made up of several fundamental pieces. In ggplot2, they are:

one quirk of ggplot is that instead of the %>% pipe command , it uses + instead. Hadley has said this will be changed in future versions, but for now, we have to use the other.

Building you graph in pieces using gapminder

If you may need to install these packages before you can use them.

Gapminder is a datast made famous in a viral 2010 TED talk. It contains the life expectency by country for 200 years, compared with several other data points. It only goes to 2002, but it’s worth using as a good example.

Subset to just the latest years

#install.packages("gapminder")
library(gapminder)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.0.0     ✔ purrr   0.2.5
## ✔ tibble  1.4.2     ✔ dplyr   0.7.6
## ✔ tidyr   0.8.1     ✔ stringr 1.3.1
## ✔ readr   1.1.1     ✔ forcats 0.3.0
## ── Conflicts ────────────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(ggplot2)

#what is gapminder? Life expectancy by country, only goes to 2002. Take the latest year.
gapminder_2002 <-
  gapminder %>%
  filter ( year == 2002)

head(gapminder_2002)

The histogram

One of the first pieces of information you often want about a dataset is its distribution. Do all of the values cluster around the center? Or do they spread out? Let’s do a histogram of the life expectency variable.

As Matt Waite shows, try just plotting the items and see where they fall.

Start your plot with the commmand ggplot, then add in the aesthetics and geometry:

ggplot( 
        data=gapminder_2002,
        aes(x = lifeExp )
      ) +
      geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

We’ll add a few options to this plot to make it a little easier to read

#make it an outline, with smaller piles.
ggplot ( data= gapminder_2002,
         aes (x= lifeExp)
        ) +
        geom_histogram (binwidth=5, color="black", fill="white")   

But I’m interested in how the different continents look. Try “faceting” by continent.

ggplot ( data= gapminder_2002,
         aes (x= lifeExp)
        ) +
        geom_histogram (binwidth=5, color="black", fill="white")   +
        facet_wrap ( ~ continent)

Try a scatter, or dot plot

Save a plot and add to it

You can save your plot to an object rather than print it immediately, making it a little easier to troubleshoot.

my_plot <-
  ggplot (
    data = gapminder_2002,
    aes (x= gdpPercap , y = lifeExp)
  )

#what does this look like?
my_plot

It doesn’t look like anything! The reason is that I didn’t include a geometry, or a shape, for the values. Add a point here:

my_plot <-
  my_plot +
  geom_point()

my_plot

There are some built-in themes that take some best practices for mixes of colors and styles, so I’ll add one in.

my_plot <-
  my_plot +
  theme_minimal()

my_plot

Let’s start over and add some color - we’re not saving it anymore, just printing it right away.

my_plot <- 
  my_plot +
  aes (color = continent)

my_plot

And now add population for the size of the country

my_plot <- 
  my_plot +
  aes (size=pop)
    
my_plot

Let’s build this from scratch, and then also make sure that the big points don’t overlap the little ones too much:

my_plot <- 
  ggplot (  data= gapminder_2002 , 
            aes ( x= gdpPercap, 
                  y = lifeExp, 
                  color = continent,
                  size = pop)
            ) +
  geom_point (alpha = 0.7) +
  theme_minimal()
  
  
my_plot

Facet

Now let’s make a little chart for each continent

my_plot <- 
  my_plot + 
  facet_wrap (~continent)


my_plot

Scale

It’s hard to see because the gdp is so skewed. That can be fixed with something called a log scale – it’s in logarithms, not base 10 numbers.

my_plot + 
  scale_x_log10()

Adding interactivity

GGPLOT2 is not interactive, so we have to install a different library to allow us to hover over the points. In this case, we’re going to use a function called paste, which puts words together, in the variable in aes called “text”:

#install.packages("plotly")
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
my_plot <-
  ggplot (data = gapminder_2002,
          aes(text = paste("country: ", country),
              x= gdpPercap ,
              y = lifeExp,
              color= continent,
              size=pop)
        ) +

    geom_point( alpha= 0.7) +
    theme_minimal() +
    facet_wrap (~continent) +
    scale_x_log10()

#We have to make it a ggplotly to get it interactive.
my_plot <- ggplotly(my_plot)

my_plot

If you want to look at lots more examples, check out Matt Waite’s data visualization course on Github